/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.jasoet.controller;

import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.jasoet.model.Penerbit;
import org.jasoet.provider.SessionFactoryProvider;

/**
 *
 * @author Deny Prasetyo
 */
public class PenerbitController {

    private SessionFactory sessionFactory;
    private Transaction tx;

    public PenerbitController() throws HibernateException {
        sessionFactory = SessionFactoryProvider.getInstance().getSessionFactory();
    }

    public PenerbitController(SessionFactory sessionFactory) throws HibernateException {
        if (sessionFactory == null) {
            sessionFactory = SessionFactoryProvider.getInstance().getSessionFactory();
        } else if (sessionFactory.isClosed()) {
            sessionFactory = SessionFactoryProvider.getInstance().getSessionFactory();
        } else {
            this.sessionFactory = sessionFactory;
        }
    }

    public void insert(Penerbit b) throws HibernateException {
        Session s = sessionFactory.openSession();
        try {
            tx = s.beginTransaction();
            s.save(b);
            tx.commit();
            tx = null;
        } catch (HibernateException ex) {
            if (tx != null) {
                tx.rollback();
            }
            throw ex;
        } finally {
            s.close();
        }
    }

    public void delete(String kode) throws HibernateException {
        Session s = sessionFactory.openSession();
        Penerbit penerbit = (Penerbit) s.load(Penerbit.class, kode);

        try {
            tx = s.beginTransaction();
            if (penerbit != null) {
                s.delete(penerbit);
                tx.commit();
                tx = null;
            } else {
                tx = null;
            }
        } catch (HibernateException ex) {
            if (tx != null) {
                tx.rollback();
            }
            throw ex;
        } finally {
            s.close();
        }
    }

    public Penerbit load(String kode) throws HibernateException {
        Session s = sessionFactory.openSession();
        Penerbit penerbit = (Penerbit) s.load(Penerbit.class, kode);
        return penerbit;
    }

    public List<Penerbit> loadAll() throws HibernateException {
        Session s = sessionFactory.openSession();
        List<Penerbit> result = s.createQuery("from Penerbit").list();
        return result;
    }

    public void closeSessionFactory() {
        if (sessionFactory != null) {
            if (!sessionFactory.isClosed()) {
                sessionFactory.close();
            }
        }
    }
}
